﻿using G.Model;
using GameControls;

namespace GameDesignControls
{
    class GameDisplayerDT : GameDisplayer 
    {

        public GameDisplayerDT(GameSpaceDef game, BoardShapeContainer container, int pSquareSize) :
            base(game, container, pSquareSize)
        {
            game.GamePlayerDefs.PlayerRemovedEvent += this.OnPlayerRemovedHandler;
            game.GameElementDefs.ElementRemovedEvent += this.OnElementRemoved;
            game.GlobalDef.Changed += OnGlobalDefChanged;
            Init();
        }
        
        public override void Dispose()
        {
            base.GameDef.GamePlayerDefs.PlayerRemovedEvent -= this.OnPlayerRemovedHandler;
            base.GameDef.GameElementDefs.ElementRemovedEvent -= this.OnElementRemoved;
            base.GameDef.GlobalDef.Changed -= OnGlobalDefChanged;
        }

        private void OnGlobalDefChanged(GameSpaceDef def)
        {
            foreach (BoardShapeDisplayer displayer in base.Displayers)
            {
                displayer.DisplayIcon();
            }
        }
            
        private void OnPlayerRemovedHandler(GamePlayerDef player)
        {
            if (base.ActiveObject.SelectedObject == player)
            {
                base.ActiveObject.SelectedObject = null;
            }
        }

        private void OnElementRemoved(GameElementDef subject)
        {
            if (base.ActiveObject.SelectedObject == subject)
            {
                base.ActiveObject.SelectedObject = null;
            }

            foreach (BoardShapeDisplayer displayer in base.Displayers)
            {
                if (displayer.Location == subject.Location)
                {
                    displayer.Clear();
                    break;
                }
            }
        }
   
        protected override BoardShapeDisplayer CreateDisplayer(BoardShape shape)
        {
            return new BoardShapeDisplayerDT(this, shape, base.ShapeContainer);
        }
        
    }
}
